package com.itheima.response;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * response响应字节数据：设置字节数据的响应体
 */
@WebServlet("/ResponseDemo4")
public class ResponseDemo4 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //使用输入流从本地获取一张图片，加载到内存中
        FileInputStream jpg = new FileInputStream("F://1.jpg");

        //获取response输出流
        ServletOutputStream outputStream = response.getOutputStream();

        //完成流的copy，将图片输出到页面
//        byte [] bytes=new byte[1024];
//        int len=0;
//        while ((len=jpg.read(bytes))!=-1){
//            outputStream.write(bytes,0,len);
//        }

        //使用工具类完成流的copy
        IOUtils.copy(jpg,outputStream);
        //关闭input输出流
        jpg.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}